package com.push.graph.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.neo4j.driver.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

public class ExcelToNeo4jImporter {

    public static void main(String[] args) {
        try {
            // 1. 读取 Excel 表格
            InputStream inputStream = new FileInputStream("D:\\桌面\\研究生\\2. 所内事务\\1. 项目申报\\科普项目\\code\\sciencepop-java\\push-graph\\src\\main\\java\\com\\push\\graph\\utils\\neo4j_test.xlsx");
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 假设数据在第一个工作表中

            // 2. 配置 Neo4j 连接
            String uri = "bolt://8.140.149.98:7687";
            String username = "neo4j";
            String password = "password";
            Driver driver = GraphDatabase.driver(uri, AuthTokens.basic(username, password));
            Session session = driver.session();

            // 3. 遍历 Excel 表格中的每一行数据，并将其转换为 Neo4j 实体
            Iterator<Row> rowIterator = sheet.rowIterator();
            Row header = rowIterator.next();
            Iterator<Cell> cellIterator = header.cellIterator();
            ArrayList<String> tableHeader = new ArrayList<>();
            while(cellIterator.hasNext()) {
                tableHeader.add(cellIterator.next().getStringCellValue());
            }
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                JSONObject object = TransformUtil.Row2JSONObject(row, tableHeader);
                String jsonString = TransformUtil.JSONObject2Neo4jString(object);

                // 4. 创建 Cypher 查询语句，将数据写入 Neo4j 数据库
                String cypherQuery = "CREATE (n:Node " + jsonString + ")";
                session.run(cypherQuery);
            }
//            String cypherQuery = String.format("CREATE (n:Node "  + object.toJSONString() + ")");
//            session.run(cypherQuery);

            // 5. 关闭 Neo4j 会话和驱动程序
            session.close();
            driver.close();

            // 6. 关闭 Excel 文件流
            workbook.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
